package com.five.config.security;

import com.five.domain.SysPermission;
import com.five.service.PermissionService;
import com.five.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

@Component
public class MyPermissionEvaluator implements PermissionEvaluator {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean hasPermission(Authentication authentication, Object o, Object o1) {
        // 获得loadUserByUsername()方法的结果
        User user = (User)authentication.getPrincipal();
        // 获得loadUserByUsername()中注入的角色
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        // 遍历用户所有角色
        for(GrantedAuthority authority : authorities) {
            String name = authority.getAuthority();
            Integer id = roleService.queryRoleByName(name).getId();
            // 得到角色所有的权限
            List<SysPermission> permissions = permissionService.queryPermissionByRoleId(1,id);

            // 遍历permissionList
            for(SysPermission permission : permissions) {
                // 如果访问的Url和权限用户符合的话，返回true
                if(o1==null){
                    if(o.equals(permission.getHref())) {
                        return true;
                    }
                }
                else if(o.equals(permission.getHref()) && o1.equals(permission.getPercode())) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}
